package com.three.iot.rest.filter;

import com.alibaba.fastjson.JSONObject;
import com.three.iot.api.DataStoreService;
import com.three.iot.commons.enums.IfAdminEnum;
import com.three.iot.commons.po.UserInfo;
import com.three.iot.rest.constants.SsoConstant;
import org.apache.shiro.web.filter.authc.UserFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author luiz
 * @Title: SsoTokenFilter
 * @ProjectName csuser
 * @Description: TODO
 * @date 2018/10/26 14:35
 */
public class SsoTokenFilter extends UserFilter {

    private DataStoreService dataStoreService;

    private static Logger logger = LoggerFactory.getLogger(SsoTokenFilter.class);

    public SsoTokenFilter(DataStoreService dataStoreService) {
        this.dataStoreService = dataStoreService;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        String resultJson = JSONObject.toJSONString(SsoConstant.SSO_LOGIN_FAIL_RESULT);
        logger.info("[sso-client]尚未登录:{}", resultJson);
        // response
        HttpServletResponse res = (HttpServletResponse) response;
        try {
            res.setStatus(HttpServletResponse.SC_OK);
            res.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(resultJson);
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("[sso-client]尚未登录,发生异常:{}", e);
        }
        return false;
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object mappedValue) {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        String link = req.getRequestURL().toString();
        /**解决跨域问题 begin**/
        String reqOriginRealPath = req.getHeader("Referer");
        String reqPath = "*";
        if (reqOriginRealPath != null) {
            int len = reqOriginRealPath.indexOf("/", 7);
            reqPath = reqOriginRealPath.substring(0, len);
        } else {
            reqPath = req.getHeader("Origin");
        }
        res.setStatus(HttpServletResponse.SC_OK);
        res.setContentType("application/json;charset=UTF-8");
        res.setHeader("Access-Control-Allow-Origin", reqPath);
        res.setHeader("Access-Control-Allow-Credentials", "true");
        res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT");
        res.setHeader("Access-Control-Max-Age", "86400");
        res.setHeader("Access-Control-Allow-Headers", "Accept,Authorization,Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,cs_sso_tokenid,userId,token");
        res.setHeader("XDomainRequestAllowed", "1");
        /**解决跨域问题 end**/
        if (req.getMethod().equals("OPTIONS")) {
            return true;
        }
        if (this.isLoginRequest(req, res)) {
            return true;
        } else {
            String tokenId = req.getHeader(SsoConstant.SSO_TOKENID);
            String userInfoStr = dataStoreService.getVal(tokenId);
            logger.info("[sso-client]请求地址:{},tokenId:{}", link, tokenId);
            // login filter
            if (userInfoStr == null) {
                return false;
            }
            UserInfo userInfo=JSONObject.parseObject(userInfoStr,UserInfo.class);
            if(link.contains("/admin")){
                if(IfAdminEnum.YES.getCode()!=userInfo.getIfAdmin()){
                    return false;
                }
            }
            dataStoreService.put(tokenId,userInfoStr);
            return true;
        }
    }
}
